package com.qianfeng.smartmetting.authiority;

import com.qianfeng.smartmetting.config.DBUserDetailsManager;
import com.qianfeng.smartmetting.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//前端传递过来的token和当前用户的校验
public class JwtAuthenticationFilter extends OncePerRequestFilter  {

    private JwtUtil jwtUtil;

    private UserDetailsService service;

    public JwtAuthenticationFilter(UserDetailsService service) {
        jwtUtil = new JwtUtil();
        this.service = service;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
            , FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = getToken(httpServletRequest);
        //判断token是否存在
        try{

            if (!StringUtils.isEmpty(token)&& jwtUtil.validateToken(token)){
                //通过token 获取token中的用户名(唯一标识)
                String username = jwtUtil.getUsernameFromToken(token);
                //通过用户名获取UserDetails
                UserDetails userDetails = service.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }else{
                //过滤登录页面/login
                if (!"/user/login".equals(httpServletRequest.getRequestURI())
                        && !"/user/add".equals(httpServletRequest.getRequestURI())){
                    httpServletResponse.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid token");
                }
            }
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }catch (Exception e){
            e.printStackTrace();
            httpServletResponse.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid token");
        }
    }

    //获取request中的token信息
    private String getToken(HttpServletRequest request){

        String token = request.getHeader("Authorization");
        //Bearer jwt默认会在前面有一个这个声明
        if (StringUtils.hasText(token) && token.startsWith("Bearer ")){
            return token.substring(7);
        }
        return null;
    }
}
